package com.party.jackclientandroid.utils;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

/**
 * Created by Administrator on 2018/9/3.
 */

public class CommonUtil {
    private static String[] week = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
    private static boolean[] week2 = new boolean[7];
    private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private static final int MIN_DELAY_TIME = 500;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime;


    private static long firstTime;

    public static boolean dupCommit() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 1000L) {
            firstTime = secondTime;
            return false;
        }
        return true;
    }


    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    public static String getUseDate(String data) {
        if (data == null || data.trim().length() == 0) {
            return "";
        }
        StringBuffer useDate = new StringBuffer("（");
        String[] arr = data.split(",");
        if (arr.length < 4) {
            for (int i = 0; i < arr.length; i++) {
                int index = Integer.parseInt(arr[i]) - 1;
                if (i == arr.length - 1) {
                    if (index < 7 && index >= 0) {
                        useDate.append(week[index] + "可用）");
                    } else {
                        return "";
                    }
                } else {
                    if (index < 7 && index >= 0) {
                        useDate.append(week[Integer.parseInt(arr[i]) - 1] + "、");
                    } else {
                        return "";
                    }
                }
            }
        } else if (arr.length == 7) {
            useDate.append("日期不限）");
        } else if (arr.length >= 4 && arr.length < 7) {
            for (int i = 0; i < arr.length; i++) {
                week2[Integer.parseInt(arr[i]) - 1] = true;
            }
            for (int i = 0; i < 7; i++) {
                if (week2[i] == false) {
                    useDate.append(week[i] + "、");
                }
                week2[i] = false;
            }
            useDate.deleteCharAt(useDate.length() - 1).append("不可用）");
        }
        return useDate.toString();
    }


    public static String getOnceCount(int data) {
        if (data > 1) {
            return "可叠加";
        } else {
            return "不可叠加";
        }
    }

    public static String getAppointment(int data) {
        String appointment = null;
        switch (data) {
            case 1:
                appointment = "免预约，座满时需排队";
                break;
            case 2:
                appointment = "电话预约";
                break;
        }
        return appointment;
    }

    public static String getAvailableDate(String data) {
        if (data == null || data.trim().length() == 0) {
            return "";
        }
        if (data.equals("1,2,3,4,5")) {
            return "周六周日不可用";
        }
        if (data.equals("1,2,3,4,5,6")) {
            return "周日不可用";
        }
        StringBuffer availableDate = new StringBuffer();
        String[] arr = data.split(",");

        if (arr.length == 7) {
            return "日期不限";
        }
        for (int i = 0; i < arr.length; i++) {
            int index = Integer.parseInt(arr[i]) - 1;
            if (index < 7 && index >= 0) {
                if (i == arr.length - 1) {
                    availableDate.append(week[index] + "可用");
                } else {
                    availableDate.append(week[Integer.parseInt(arr[i]) - 1] + "、");
                }
            } else {
                return null;
            }
        }

        return availableDate.toString();
    }

    public static String formatTime(Long timeStamp) {
        return df.format(timeStamp);
    }


    /**
     * 优惠买单计算公式
     *
     * @param consumeSum 消费总额
     * @param notAdd     不参与优惠金额
     * @param favMoney   代金券金额
     * @param discount   折扣
     * @return
     */
    public static double favourablePayBill(double consumeSum, double notAdd, double favMoney, double discount) {
        return (consumeSum - notAdd - favMoney) * discount + notAdd;
    }

    /**
     * 判断字符串是否是数字
     */
    public static boolean isNumber(String value) {
        return isInteger(value) || isDouble(value);
    }

    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是浮点数
     */
    public static boolean isDouble(String value) {
        try {
            Double.parseDouble(value);
            if (value.contains("."))
                return true;
            return false;
        } catch (NumberFormatException e) {
            return false;
        }
    }


    /**
     * 将数据保留两位小数
     */
    public static double getTwoDecimal(double num) {
        DecimalFormat dFormat = new DecimalFormat("#.00");
        String yearString = dFormat.format(num);
        Double temp = Double.valueOf(yearString);
        return temp;
    }

    /**
     * 时间处理
     *
     * @param time
     * @return
     */
    public static String validateTime(int time) {
        return time < 10 ? "0" + time : "" + time;
    }

    public static String getOrderState(int orderId) {
        String orderStateStr = null;
        switch (orderId) {
            case -1:
                orderStateStr = "全部";
                break;
            case 1:
                orderStateStr = "待付款";
                break;
            case 2:
                orderStateStr = "待使用";
                break;
            case 3:
                orderStateStr = "待评价";
                break;
            case 6:
                orderStateStr = "退款中";
                break;
            case 7:
                orderStateStr = "退款";
        }
        return orderStateStr;
    }

    public static int getOrderTypeId(String orderState) {
        int orderTypeId = -1;
        if (orderState.equals("全部")) {
            orderTypeId = -1;
        } else if (orderState.equals("待付款")) {
            orderTypeId = 1;
        } else if (orderState.equals("待使用")) {
            orderTypeId = 2;
        } else if (orderState.equals("待评价")) {
            orderTypeId = 3;
        } else if (orderState.equals("退款中")) {
            orderTypeId = 6;
        } else if (orderState.equals("退款")) {
            orderTypeId = 7;
        }
        return orderTypeId;
    }

    /**
     * 根据图片的url路径获得Bitmap对象
     *
     * @param url
     * @return
     */
    public static Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum
     * @param activity
     */
    public void callPhone(String phoneNum, Activity activity) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        activity.startActivity(intent);
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isGPSOpen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps && network) {
            return true;
        }
        return false;
    }

    /**
     * 强制帮用户打开GPS
     *
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }


    public static String getGoodsRange(String range) {
        return range == null ? "全场通用" : range;
    }

    public static void finishLoading(SmartRefreshLayout mRefreshLayout) {
    }
}
